import { AuthService } from './authService';
import * as vscode from 'vscode';

// 从 extension.ts 移植 getUserMap
export async function getUserMap(context: vscode.ExtensionContext, forceRefresh = false): Promise<any[]> {
  const USER_MAP_URL = 'https://test-jobs.cyouops.com/config_center/api/v1/configs/demo/code.review/';
  const USER_MAP_KEY = 'userMapCache';
  const USER_MAP_EXPIRE_MS = 60 * 60 * 1000;
  const Logger = (await import('./logger')).Logger;
  const logger = Logger.getInstance();
  const now = Date.now();
  if (!forceRefresh) {
    const cache = context.globalState.get<{ data: any[], expires: number }>(USER_MAP_KEY);
    if (cache && Array.isArray(cache.data) && cache.expires > now) {
      logger.info(`[getUserMap] 使用本地缓存, 剩余: ${(cache.expires - now) / 1000}s`);
      return cache.data;
    }
  }
  logger.info('[getUserMap] 拉取远程用户映射表...');
  const axios = require('axios');
  let userMapResp;
  try{
    userMapResp = await axios.get(USER_MAP_URL, {
    headers: {
      'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
      'Accept': '*/*',
      'Host': 'test-jobs.cyouops.com',
      'Connection': 'keep-alive'
    },
    timeout: 10000
  });
  }catch(e:any){
  const logger = (await import('./logger')).Logger.getInstance();
  logger.error('[getUserMap] 拉取用户映射表失败', e);
  if (e.response && e.response.status === 502) {
    vscode.window.showErrorMessage('服务暂不可用，请稍后再试');
  } else {
    vscode.window.showErrorMessage('拉取用户映射表失败: ' + (e.message || e.toString()));
  }
  return [];
  }
  const usersObj = userMapResp.data?.data?.configurations?.users;
  console.log('[getUserMap] usersObj:', usersObj);
  if (!usersObj) throw new Error('未获取到用户映射表');
  const peopleArr = usersObj.people || [];
  await context.globalState.update(USER_MAP_KEY, { data: peopleArr, expires: now + USER_MAP_EXPIRE_MS });
  logger.info(`[getUserMap] 远程拉取并缓存, 人数: ${peopleArr.length}`);
  return peopleArr;
}

export async function getCurrentUserId(context: vscode.ExtensionContext, authService: AuthService): Promise<number> {
  const peopleArr = await getUserMap(context);
  const user = await authService.getCurrentUser();
  if (!user || !user.name) throw new Error('未获取到当前用户信息');
  const normalize = (s: string) => s.replace(/\\/g, '').trim();
  const currentName = normalize(user.name);
  const found = peopleArr.find((p: any) => normalize(p.name) === currentName);
  if (!found) throw new Error(`未在用户映射表中找到当前用户: ${user.name}`);
  return found.userId;
} 